package com.jason.www.service.impl;


import com.jason.www.service.ISendEmailService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.core.task.TaskRejectedException;
import org.springframework.stereotype.Service;

@Service
public class SendEmailServiceImpl implements ISendEmailService {
    protected final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Autowired
    TaskExecutor taskExecutor;

    @Override
    public void sendRegEmail(String userName) {
        String code = genRandomCode();
        try {
            taskExecutor.execute(()->{
                //System.out.println("你好，" + userName + "您的账号注册验证码为" + code);
                LOGGER.info("你好，" + userName + "您的账号注册验证码为" + code);
            });
        }catch (TaskRejectedException ex){
            LOGGER.error("sendRegEmail异步信息异常：" + ex.getMessage());
        }

    }

    @Override
    public void sendResetPswEmail(String userName) {
        String code = genRandomCode();
        try {
            taskExecutor.execute(()->{sendResetPswEmail(userName,code);});
        }catch (TaskRejectedException ex){
            LOGGER.error("sendResetPswEmail异步信息异常：" + ex.getMessage());
        }
    }

    private void sendResetPswEmail(String userName ,String code) {
        //System.out.println("你好，" + userName + "您的重置密码操作验证码为" + code);
        LOGGER.info("你好，" + userName + "您的重置密码操作验证码为" + code);
    }

    private static String genRandomCode() {
        //验证码的位数
        Integer num = 4;
        StringBuffer code = new StringBuffer();
        for(int i=0 ; i<num ; i++){
            while (true){
                //根据ascii码来拿
                int temp = (int)(Math.random()*122)+48;
                if(temp >= '0' && temp <= '9' || temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <= 'z'){
                    code.append((char)temp); break;
                }
            }
        }
        return code.toString();
    }

}
